import PropTypes, { func } from 'prop-types'
import React, { memo, useState, useEffect, useRef } from 'react'
import { ViewWrapper } from './style'
import IconArrowLeft from '@/assets/svg/icon-arrow-left'
import IconArrowRight from '@/assets/svg/icon-arrow-right'

const ScrollView = memo((props) => {
    // 控制右边按钮的显示
    const [showRightBtn, setShowRightBtn] = useState(false)
    // 控制左边按钮的显示
    const [showLeftBtn, setShowLeftBtn] = useState(false)
    // 记录当前位置
    const [posIndex, setPosIndex] = useState(0)
    const totalDistanceRef = useRef()

    // 组件渲染完成后，判断是否需要显示右边按钮
    const scrollContentRef = useRef()
    useEffect(() => {
        const scrollWidth = scrollContentRef.current.scrollWidth
        const clientWidth = scrollContentRef.current.clientWidth
        const totalDistance = scrollWidth - clientWidth
        totalDistanceRef.current = totalDistance
        setShowRightBtn(totalDistance > 0)
    }, [props.children])

    // 控制显示按钮点击事件
    function controlClickHandle(isRight) {
        let newIndex = isRight ? posIndex + 1 : posIndex - 1
        const newEl = scrollContentRef.current.children[newIndex]
        const newOffsetLeft = newEl.offsetLeft
        scrollContentRef.current.style.transform = `translate(-${newOffsetLeft}px)`
        setPosIndex(newIndex)
        // 判断是否继续显示按钮
        setShowRightBtn(totalDistanceRef.current > newOffsetLeft)
        setShowLeftBtn(newOffsetLeft > 0)
    }

    return (
        <ViewWrapper>
            {showLeftBtn && (
                <div className='control left' onClick={e => controlClickHandle(false)}>
                    <IconArrowLeft />
                </div>
            )}
            {showRightBtn && (
                <div className='control right' onClick={e => controlClickHandle(true)}>
                    <IconArrowRight />
                </div>
            )}

            <div className='scroll'>
                <div className="slot-content" ref={scrollContentRef}>
                    {props.children}
                </div>
            </div>
        </ViewWrapper>
    )
})

ScrollView.propTypes = {}

export default ScrollView